<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Python函数式编程之 update_in_fn - (power up)</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Kevin Jiang" /><meta name="description" content="接上一篇内容 Python函数式编程之自定义函数get_in 。这次我们来编写函数式风格的修改字典/列表值的通用函数。 我们先来假设一种情况，你有" /><meta name="keywords" content="KevinJiang, AI大模型, AI落地, 全栈工程师, Java, Spring Boot" />






<meta name="generator" content="Hugo 0.84.4 with theme even" />


<link rel="canonical" href="http://kevinjiang.info/post/python/python%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E4%B9%8Bupdate_in_fn/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.78f8f17bab244b9ee62ad16480c9584d5fc2db06ae20681d1ca225cefd80767c.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="Python函数式编程之 update_in_fn" />
<meta property="og:description" content="接上一篇内容 Python函数式编程之自定义函数get_in 。这次我们来编写函数式风格的修改字典/列表值的通用函数。 我们先来假设一种情况，你有" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://kevinjiang.info/post/python/python%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E4%B9%8Bupdate_in_fn/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2023-05-19T20:53:42+08:00" />
<meta property="article:modified_time" content="2023-05-19T20:53:42+08:00" />

<meta itemprop="name" content="Python函数式编程之 update_in_fn">
<meta itemprop="description" content="接上一篇内容 Python函数式编程之自定义函数get_in 。这次我们来编写函数式风格的修改字典/列表值的通用函数。 我们先来假设一种情况，你有"><meta itemprop="datePublished" content="2023-05-19T20:53:42+08:00" />
<meta itemprop="dateModified" content="2023-05-19T20:53:42+08:00" />
<meta itemprop="wordCount" content="1445">
<meta itemprop="keywords" content="SSH,SSH会话,SSH客户端," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Python函数式编程之 update_in_fn"/>
<meta name="twitter:description" content="接上一篇内容 Python函数式编程之自定义函数get_in 。这次我们来编写函数式风格的修改字典/列表值的通用函数。 我们先来假设一种情况，你有"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">(Power up)</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">归档</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/resume/">
        <li class="mobile-menu-item">简历</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">(Power up)</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/resume/">简历</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">Python函数式编程之 update_in_fn</h1>

      <div class="post-meta">
        <span class="post-time"> 2023-05-19 </span>
        <div class="post-category">
            <a href="/categories/linux/"> Linux </a>
            </div>
          <span class="more-meta"> 约 1445 字 </span>
          <span class="more-meta"> 预计阅读 3 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#对update_in函数解释一下">对update_in函数解释一下</a></li>
    <li><a href="#来看几个例子">来看几个例子</a></li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>接上一篇内容 <a href="/post/python/python%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E4%B9%8B%E8%87%AA%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0get_in">Python函数式编程之自定义函数get_in</a> 。这次我们来编写函数式风格的修改字典/列表值的通用函数。</p>
<p>我们先来假设一种情况，你有一个嵌套的动态字典，想要更新里面某个键对应的值，我们用代码来说明</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">}}</span>
</code></pre></td></tr></table>
</div>
</div><p>现在有一个变量<code>data</code> 他的值是一个两层的字典，如果我要更新 <code>b</code> 的值到 <code>2</code> 常规的做法是这样的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span><span class="p">[</span><span class="s1">&#39;a][&#39;</span><span class="sa">b</span><span class="s1">&#39;] = 2</span>
</code></pre></td></tr></table>
</div>
</div><p>如果我有一个更加深的字典</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;d&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">}}}}</span>
</code></pre></td></tr></table>
</div>
</div><p>更新值的写法</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">][</span><span class="s1">&#39;b&#39;</span><span class="p">][</span><span class="s1">&#39;c&#39;</span><span class="p">][</span><span class="s1">&#39;d&#39;&#39;] = 2</span>
</code></pre></td></tr></table>
</div>
</div><p>这里有一个情况发生了，当 <code>data</code> 是一个动态数组，你不确定中间的某个键是否存在的时候就会有报错</p>
<p><img src="/img/Python/nested_dict_update.png" alt="嵌套字典更新"></p>
<p>假如这个数据是你的系统里面其他团队开发的一个微服务，报错的信息是<code>int</code> 对象是不可读取索引的，这会让人很奇怪，2这个int对象明明是一个值，而不是用来查找索引数据的。</p>
<p>这时候程序的健壮性是比较差的，要想让程序保证健壮，我们可以使用 <code>if-else</code> 来判断每个键是否存在，就像这样</p>
<p><img src="/img/Python/nested_dict_update_if_else.png" alt="嵌套字典更新"></p>
<p>这里的三个<code>if</code> 看起来一点都不够优雅，如果其他地方也有同样的写法，只是键的顺序和名字不一样而已呢。能不能封装一个通用的函数来处理类似的情况呢？</p>
<h1 id="update_in">update_in</h1>
<p>Python支持面向过程、面向对象、函数式等多范式编程。我们可以使用函数式编程思想来达到这一点。先来看一个简单一点的 <code>update_in</code> 函数</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Dict</span><span class="p">,</span> <span class="n">List</span><span class="p">,</span> <span class="n">T</span>

<span class="k">def</span> <span class="nf">update_in</span><span class="p">(</span><span class="n">data</span><span class="p">:</span> <span class="n">Dict</span><span class="p">,</span> <span class="n">ks</span><span class="p">:</span> <span class="n">List</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span>
    <span class="s2">&#34;&#34;&#34;Updates a value in a nested associative structure.
</span><span class="s2">
</span><span class="s2">    Args:
</span><span class="s2">        data (Dict): nested associative structure
</span><span class="s2">        ks (List): sequence of keys
</span><span class="s2">        value (Any): new value
</span><span class="s2">    &#34;&#34;&#34;</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">ks</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">return</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">data</span>
    <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">ks</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]:</span>
        <span class="k">if</span> <span class="n">k</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">cursor</span><span class="p">:</span>
            <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">elif</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">],</span> <span class="nb">dict</span><span class="p">):</span>
            <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span>
    <span class="n">cursor</span><span class="p">[</span><span class="n">ks</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]]</span> <span class="o">=</span> <span class="n">value</span>
</code></pre></td></tr></table>
</div>
</div><blockquote>
<p>这里有一个类型 <code>T</code> ，这是Python内置的任意类型，在 <code>typing</code> 模块可以看到定义 <code>T = TypeVar('T')</code></p>
</blockquote>
<h2 id="对update_in函数解释一下">对update_in函数解释一下</h2>
<p>首先判断键序列是否为空，为空的话什么也不做。然后使用一个游标<code>cursor</code>来指定当前取得是字典所在的位置，然后不停的循环下去，拿到除最后一个键之外的值。在最后把值赋给找到的最后一个键所指定的值。</p>
<h2 id="来看几个例子">来看几个例子</h2>
<p>来看几个例子，了解函数的作用。假设我有一个空字典 <code>data = dict()</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">update_in</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>执行完成<code>update_in</code>函数后，data的值为 <code>{'a': 1}</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">update_in</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">],</span> <span class="mi">2</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>执行完后，data的值为 <code>{'a': {'b': 1}}</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">update_in</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">],</span> <span class="mi">3</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>执行完后，data的值为 <code>{'a': {'b': {'c': {'d': 3}}}}</code></p>
<p>我们封装了一个通用函数，可以对任意的字典，任意的键序列进行值的修改。</p>
<p>再更进一步，如果不是单纯的给某个键序列进行赋值，而是要取出那个值，然后再进行一些变换呢？比如，我要取出 <code>['a', 'b']</code> 对应的值，进行一个平方计算，或者取个对数呢？我们增加一个参数，变成<code>update_in_fn</code>函数</p>
<h1 id="update_in_fn">update_in_fn</h1>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Dict</span><span class="p">,</span> <span class="n">List</span><span class="p">,</span> <span class="n">Callable</span><span class="p">,</span> <span class="n">T</span>

<span class="k">def</span> <span class="nf">update_in_fn</span><span class="p">(</span><span class="n">data</span><span class="p">:</span> <span class="n">Dict</span><span class="p">,</span> <span class="n">ks</span><span class="p">:</span> <span class="n">List</span><span class="p">,</span> <span class="n">fn</span><span class="p">:</span> <span class="n">Callable</span><span class="p">,</span> <span class="n">default</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span>
    <span class="s2">&#34;&#34;&#34;Updates a value in a nested associative structure.
</span><span class="s2">
</span><span class="s2">    Args:
</span><span class="s2">        data (Dict): nested associative structure
</span><span class="s2">        ks (List): sequence of keys
</span><span class="s2">        fn (Callable): take the old value and return the new value
</span><span class="s2">        default (Any): default value
</span><span class="s2">
</span><span class="s2">    Examples:
</span><span class="s2">        &gt;&gt;&gt; a = </span><span class="si">{}</span><span class="s2">
</span><span class="s2">        &gt;&gt;&gt; update_in_fn(a, [&#39;a&#39;, &#39;b&#39;], lambda x: x + 1, default=0)
</span><span class="s2">        &gt;&gt;&gt; assert a == {&#39;a&#39;: {&#39;b&#39;: 0}}
</span><span class="s2">    &#34;&#34;&#34;</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">ks</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">return</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">data</span>
    <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">ks</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]:</span>
        <span class="k">if</span> <span class="n">k</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">cursor</span><span class="p">:</span>
            <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">elif</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">],</span> <span class="nb">dict</span><span class="p">):</span>
            <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="n">cursor</span><span class="p">[</span><span class="n">k</span><span class="p">]</span>
    <span class="n">key</span> <span class="o">=</span> <span class="n">ks</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">if</span> <span class="n">key</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">cursor</span><span class="p">:</span>
        <span class="n">cursor</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">default</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">cursor</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">fn</span><span class="p">(</span><span class="n">cursor</span><span class="p">[</span><span class="n">key</span><span class="p">])</span>
</code></pre></td></tr></table>
</div>
</div><p>我们对这个函数加以说明：</p>
<p>第一个参数是被修改的字典数据</p>
<p>第二个参数是键序列</p>
<p>第三个参数是一个可调用函数，传入一个参数，返回一个结果</p>
<p>第三个参数表明如果字典里面没有找到对应的值，使用default填充键序列指定的那个位置的值</p>
<p>还是使用几个例子来说明用法及结果</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">()</span>
<span class="n">update_in_fn</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">],</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="c1"># data: {&#39;a&#39;: 2}</span>
</code></pre></td></tr></table>
</div>
</div><p>在一个空字典上执行函数调用时，会填充默认的值 <code>default</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span>
<span class="n">update_in_fn</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">],</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="c1"># data: {&#39;a&#39;: 9}</span>
</code></pre></td></tr></table>
</div>
</div><p>对键 <code>'a'</code> 指定的值进行平方计算，计算后的结果为 <code>9</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">}}</span>
<span class="n">update_in_fn</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">],</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="c1"># data: {&#39;a&#39;: {&#39;b&#39;: 16}}</span>
</code></pre></td></tr></table>
</div>
</div><p>对嵌套字典里面的值进行更新，4的平方16</p>
<h1 id="结论">结论</h1>
<p>借助Python强大的函数式编程范式，我们可以编写非常通用的函数及模块，上面的两个函数代码还有优化的空间，比如用户自定义的字典类型，可以像get_in函数一样支持数组。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Kevin Jiang</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2023-05-19
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content"><a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a></span>
  </p>
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/wechat_pay_1242x1242.jpg">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/alipay_600x600.jpg">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/ssh/">SSH</a>
          <a href="/tags/ssh%E4%BC%9A%E8%AF%9D/">SSH会话</a>
          <a href="/tags/ssh%E5%AE%A2%E6%88%B7%E7%AB%AF/">SSH客户端</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/python/python&#43;docker&#43;fastapi%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E9%83%A8%E7%BD%B2restful-api/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">Python Docker FastAPI快速开发部署RESTful API</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/python/python%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E4%B9%8B%E8%87%AA%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0get_in/">
            <span class="next-text nav-default">Python函数式编程之自定义函数get_in</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:wenlin1988@126.com" class="iconfont icon-email" title="email"></a>
      <a href="https://www.linkedin.com/in/%E6%96%87%E6%9E%97-%E8%92%8B-0a3204126/" class="iconfont icon-linkedin" title="linkedin"></a>
      <a href="https://github.com/kevindragon" class="iconfont icon-github" title="github"></a>
  <a href="http://kevinjiang.info/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 -
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy;
    2015 -
    2023<span class="heart"><i class="iconfont icon-heart"></i></span><span>Kevin Jiang</span>
    <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备2022022745号</a>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        tags: 'ams',
        }
    };
  </script>
  <script type="text/javascript" async src="/lib/mathjax/es5/tex-mml-chtml.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?b73ff6d4afc4af9e582d8a5dc068bab9";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>






</body>
</html>
